package app.commonviewpagerlibrary.viewpager;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import java.util.List;

import app.commonviewpagerlibrary.adapter.CommonViewPagerAdapter;
import app.commonviewpagerlibrary.R;
import app.commonviewpagerlibrary.ViewPagerHolderCreator;
import app.commonviewpagerlibrary.indicatorview.CircleIndicatorView;
import app.commonviewpagerlibrary.indicatorview.DisplayUtils;

/**
 * Created by 刘智强 on 2017/5/31.
 */

public class CommonViewPager<T> extends RelativeLayout {
    private ViewPager mViewPager;
    private CommonViewPagerAdapter mAdapter;
    private CircleIndicatorView mCircleIndicatorView;
    private Context context;
    private boolean isCarousel = false;//是否轮播 默认不需要轮播
    private long TIME = 1800;//自动轮播的间隔时间
    private int itemPosition;//当前item的下标
    private int dataSize;//数据源的大小
    private final int BANNER_NEXT = 1001;//轮播
    private final int BANNER_PAUSE = 1002;//停止轮播
    private final int BANNER_RESUME = 1003;//继续轮播
    private MyHandle myHandle = new MyHandle();


    public boolean isCarousel() {
        return isCarousel;
    }

    public void setCarousel(boolean carousel) {
        isCarousel = carousel;
    }


    public CommonViewPager(Context context) {
        super(context);
        this.context = context;
        init();
    }

    public CommonViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    private void init() {
        View view = LayoutInflater.from(context).inflate(R.layout.common_view_pager_layout, this, true);
        mViewPager = (ViewPager) view.findViewById(R.id.common_view_pager);
        mCircleIndicatorView = (CircleIndicatorView) view.findViewById(R.id.common_view_pager_indicator_view);
        mCircleIndicatorView.setRadius(DisplayUtils.dpToPx(7));
        // 设置Border
        mCircleIndicatorView.setBorderWidth(DisplayUtils.dpToPx(2));

        // 设置文字颜色
        mCircleIndicatorView.setTextColor(Color.BLACK);
        // 设置选中颜色
        mCircleIndicatorView.setSelectColor(Color.parseColor("#FEBB50"));
        //
        mCircleIndicatorView.setDotNormalColor(Color.parseColor("#E38A7C"));
        // 设置指示器间距
        mCircleIndicatorView.setSpace(DisplayUtils.dpToPx(10));
        // 设置模式
        mCircleIndicatorView.setFillMode(CircleIndicatorView.FillMode.NONE);

        // 设置点击Indicator可以切换ViewPager
        mCircleIndicatorView.setEnableClickSwitch(true);

    }

    /**
     * 设置数据
     *
     * @param data
     * @param creator
     */
    public void setPages(List<T> data, ViewPagerHolderCreator creator) {
        dataSize = data == null ? 0 : data.size();
        mAdapter = new CommonViewPagerAdapter(data, creator);
//        if (isCarousel()) {
//            mHandler.postDelayed(runnable, TIME);
//        }
        mViewPager.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        mCircleIndicatorView.setUpWithViewPager(mViewPager);
        if (isCarousel()) {
            myHandle.sendEmptyMessageDelayed(BANNER_NEXT, TIME);
        } else {

        }
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (isCarousel()) {
                    switch (state) {
                        case ViewPager.SCROLL_STATE_DRAGGING:
                            myHandle.sendEmptyMessage(BANNER_PAUSE);
                            break;
                        case ViewPager.SCROLL_STATE_IDLE:
                            myHandle.sendEmptyMessageDelayed(BANNER_NEXT, 2000);
                            break;
                    }

                }
            }
        });
    }

    public void setCurrentItem(int currentItem) {
        mViewPager.setCurrentItem(currentItem);
    }

    public int getCurrentItem() {
        return mViewPager.getCurrentItem();
    }

    public void setOffscreenPageLimit(int limit) {
        mViewPager.setOffscreenPageLimit(limit);
    }

    /**
     * 设置切换动画，see {@link ViewPager#setPageTransformer(boolean, ViewPager.PageTransformer)}
     *
     * @param reverseDrawingOrder
     * @param transformer
     */
    public void setPageTransformer(boolean reverseDrawingOrder, ViewPager.PageTransformer transformer) {
        mViewPager.setPageTransformer(reverseDrawingOrder, transformer);
    }

    /**
     * see {@link ViewPager#setPageTransformer(boolean, ViewPager.PageTransformer)}
     *
     * @param reverseDrawingOrder
     * @param transformer
     * @param pageLayerType
     */
    public void setPageTransformer(boolean reverseDrawingOrder, ViewPager.PageTransformer transformer, int pageLayerType) {
        mViewPager.setPageTransformer(reverseDrawingOrder, transformer, pageLayerType);
    }

    /**
     * see {@link ViewPager#addOnPageChangeListener(ViewPager.OnPageChangeListener)}
     *
     * @param listener
     */
    public void addOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        mViewPager.addOnPageChangeListener(listener);
    }

    /**
     * 设置是否显示Indicator
     *
     * @param visible
     */
    private void setIndicatorVisible(boolean visible) {
        if (visible) {
            mCircleIndicatorView.setVisibility(VISIBLE);
        } else {
            mCircleIndicatorView.setVisibility(GONE);
        }

    }

    public ViewPager getViewPager() {
        return mViewPager;
    }

//    Runnable runnable = new Runnable() {
//        @Override
//        public void run() {
//
//            if (!mAdapter.isOnKeyDown()) {
//                mHandler.postDelayed(this, TIME);
//            }
//            if (dataSize == 0) {
//                try {
//                    throw new Exception("数据源大小不能为0!!!");
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//            mViewPager.setCurrentItem(itemPosition % dataSize);
//            itemPosition++;
//        }
//    };


//    @Override
//    public void postViewPager() {
////        mHandler.postDelayed(runnable, TIME);
//
//    }


    public class MyHandle extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (myHandle.hasMessages(BANNER_NEXT)) {
                myHandle.removeMessages(BANNER_NEXT);
            }
            switch (msg.what) {
                case BANNER_NEXT:
                    itemPosition++;
                    mViewPager.setCurrentItem(itemPosition % dataSize);
                    myHandle.sendEmptyMessageDelayed(BANNER_NEXT, 2000);
                    break;
                case BANNER_PAUSE:
                    break;
                case BANNER_RESUME:
                    itemPosition++;
                    mViewPager.setCurrentItem(itemPosition % dataSize);
                    myHandle.sendEmptyMessageDelayed(BANNER_NEXT, 2000);
                    break;
                default:
            }

        }
    }
}
